from django.db import models
from django.contrib.auth.models import User
from django.db.models.signals import post_save

import datetime

# Create your models here.
class Player(models.Model):
    name = models.CharField(max_length=20)
    #These will be dynamically computed from the data
    wins = models.IntegerField('wins')
    draws = models.IntegerField('draws')
    losses = models.IntegerField('losses')

    def __unicode__(self):
        return self.name


class League(models.Model):
    name = models.CharField(max_length=100)

    def __unicode__(self):
        return self.name


class Week(models.Model):
    date = models.DateField('date of first tip')    
    
    def __unicode__(self):
        return self.date.isoformat()



class Game(models.Model):
    away = models.CharField(max_length=3)
    home = models.CharField(max_length=3)
    line = models.DecimalField(max_digits = 5, decimal_places = 1) # This is the line for the home team
    week = models.ForeignKey(Week)

    def __unicode__(self):
        return self.away + ' @ ' + self.home + ' (' + str(self.line) + ')'


class Result(models.Model):    
    away_score = models.IntegerField()
    home_score = models.IntegerField()
    game = models.ForeignKey(Game)

    def __unicode__(self):
        return str(self.game) + ' ' + str(self.away_score) + ' to '+ str(self.home_score)

def log_result(sender, instance, created, **kwargs):
    picks = Pick.objects.filter(game = instance.game)
    cover = winner(instance)
    for pick in picks:
        if pick.pick == cover:
            pick.player.wins += 1
        elif cover != 'DRAW':
            pick.player.losses += 1
        else:
            pick.player.draws += 1 
        pick.player.save()

post_save.connect(log_result, sender=Result)

def winner(result):
    if (result.home_score + result.game.line) > result.away_score:
        winner = result.game.home
    elif (result.home_score + result.game.line) < result.away_score:
        winner = result.game.away
    else:
        winner = 'DRAW'
    return winner

def recalculate_records():
    reinit_records()
    for result in Result.objects.all():
        cover = winner(result)
        for pick in Pick.objects.filter(game = result.game):
            if pick.pick == cover:
                pick.player.wins += 1
            elif cover != 'DRAW':
                pick.player.losses += 1
            else:
                pick.player.draws += 1 
            pick.player.save()
            

def reinit_records():
    for player in Player.objects.all():
        player.wins = 0
        player.losses = 0
        player.draws = 0
        player.save()

class Pick(models.Model):
    game = models.ForeignKey(Game)
    player = models.ForeignKey(Player)
    pick = models.CharField(max_length=3)
# this will be security against people making picks after games start
# Can't just modify the tables
#    datetime = models.DateTimeField(auto_now_add=True)
    
    def __unicode__(self):
        return self.game.__unicode__() + ' : ' + self.player.name + ' : ' + self.pick
        
class UserProfile(models.Model):
    user = models.OneToOneField(User)

    player = models.ForeignKey(Player)

    def __unicode__(self):
        return '<up: ' + self.player.name + '>'



#def create_user_profile(sender, instance, created, **kwargs):
#    if created:
#        UserProfile.objects.create(user=instance)

#post_save.connect(create_user_profile, sender=User)
